package dwz.web.management;

//import javax.inject.Inject;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import dwz.cms.article.impl.IChannelService;
import dwz.persistence.beans.CmsChannel;
import dwz.web.BaseController;

@Controller("management.indexController")
@RequestMapping("/management")
public class IndexController extends BaseController {
	@Autowired
	private IChannelService channelService;
	
	@RequestMapping("")
	public String index(Model model) {

		// 添加时间信息
		model.addAttribute("now", new Date());
		// 查询目录列表
		List<CmsChannel> channelList = channelService.selectChannelisNotFirst();

		JSONArray jsonArray = new JSONArray();
		JSONArray jsonArrayMenuGroup = new JSONArray();

		for (CmsChannel channel : channelList) {
			System.out.println(channel.getId() + " " + channel.getFatherid() + " " + channel.getTitle());
			JSONObject jObject = new JSONObject();
			jObject.put("id", channel.getId());
			jObject.put("pId", channel.getFatherid() == 1 ? 0 : channel.getFatherid());
			jObject.put("name", channel.getTitle());
  
			if ("0".equals(jObject.get("pId").toString())) {
				jsonArrayMenuGroup.put(jObject);
			} else {
				jsonArray.put(jObject);
			}
		}
		
		StringBuffer sb = new StringBuffer();  
		Iterator itMenuGroup = (Iterator) jsonArrayMenuGroup.iterator();
		sb.append("<ul class=\"tree treeFolder\">");
		while (itMenuGroup.hasNext()) {
			JSONObject menuGroup = (JSONObject) itMenuGroup.next();
			sb.append("<li><a href=\"/cmsback/management/article/show/"+menuGroup.get("id")+"\" target=\"navTab\" rel=\"channel_"+menuGroup.get("id")+"\">"+menuGroup.get("name")+"</a>");
			Iterator itMenus = (Iterator) jsonArray.iterator();
			StringBuffer sbSecondMenu = new StringBuffer();  
			while (itMenus.hasNext()) {
				
				JSONObject menu = (JSONObject) itMenus.next();
				// 如果当前menu选项的pId与当前menuGroup的id号相等，则其为menuGroup的子菜单
				if(menu.get("pId").equals(menuGroup.get("id"))){
					sbSecondMenu.append("<li><a href=\"/cmsback/management/article/show/"+menu.get("id")+"\" target=\"navTab\" rel=\"channel_"+menu.get("id")+"\">"+menu.get("name")+"</a></li>");
				}
			}
			
			if(!"".equals(sbSecondMenu)){
				sb.append("<ul>");// 二级菜单组开始
				sb.append(sbSecondMenu);
				sb.append("</ul>");// 二级菜单组结束
			}
			
			sb.append("</li>");// 一级菜单结束
		}
		
		sb.append("</ul>");// 菜单结束
		System.out.println(sb);
		
		model.addAttribute("menuHtml", sb.toString());
		return "/ArticleManagement/index";
	}

}